package tomcat;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ThreadPool implements Runnable {
    private BlockingQueue<Runnable> queue;
    private boolean isStopped;
    private List<PoolThread> threads = new ArrayList<PoolThread>();

    public ThreadPool(int numThreads, int maxNumThreads, int numQueues) {
        queue = new ArrayBlockingQueue<>(numQueues);
        for (int i = 0; i < numThreads; i++) {
            threads.add(new PoolThread(queue, this));
        }
    }

    public void execute(Runnable task) throws InterruptedException {
        synchronized (queue) {
            while (queue.remainingCapacity() == 0) {
                queue.wait();
            }
            queue.offer(task);
            queue.notifyAll();
        }
    }

    public void shutdown() {
        isStopped = true;
        for (PoolThread thread : threads) {
            thread.doStop();
        }
    }

    public void doWork() throws InterruptedException {
        Runnable runnable;
        synchronized (queue) {
            while (queue.isEmpty()) {
                queue.wait();
            }
            runnable = (Runnable) queue.poll();
            queue.notifyAll();
        }
        if (runnable != null) {
            runnable.run();
        }
    }

    @Override
    public void run() {

    }


    // getters and setters
}